import $ from 'jquery';
import 'froala-editor';
import 'froala-editor/js/languages/zh_cn';
import 'froala-editor/js/plugins/align.min';
import 'froala-editor/js/plugins/colors.min';
import 'froala-editor/js/plugins/font_family.min';
import 'froala-editor/js/plugins/font_size.min';
import 'froala-editor/css/plugins/colors.min.css';
import backgroundUrl from '@/images/invoice_background.jpg';

import {SEALS} from '../../../config/static';


import util from '@/libs/util';
import Cookies from 'js-cookie';
import getDate from '@/util/getDate.js';

const DEFAULT_SEAL_WIDTH = 200;

export default {
    data() {
        return {
            imageDataUrl: '',
            editorInst: null,
            makeTemplate: {
                sprites: []
            },
            seals: SEALS,

            render: {
                bgOriginWidth: 0,
                bgOriginHeight: 0,
                bgScale: 1,

                previewContainerWidth: 0,
                previewContainerHeight: 0
            },

            backgroundImages: [],

            variables: [{
                name: 'name',
                placeholder: '姓名',
                text: '姓名'
            }, {
                name: 'reserve_no',
                placeholder: '预约号',
                text: '预约号'
            }, {
                name: 'amt',
                placeholder: '费用',
                text: '费用'
            }, {
                name: 'charge_date',
                placeholder: '缴费时间',
                text: '缴费时间'
            }, {
                name: 'charge_type',
                placeholder: '缴费方式',
                text: '缴费方式'
            }],

            activeSpriteIndex: -1,

            drag: {
                draggingIndex: -1,
                mouseDownX: 0,
                mouseDownY: 0,

                mouseDownSpriteX: 0,
                mouseDownSpriteY: 0,

                mouseDownSpriteWidth: 0,
                mouseDownSpriteHeight: 0,

                resizer: '', // nw | ne | sw | se
                spriteRatio: 0
            },

            bgPickerVisible: false,
            bgUrlTemp: '',
            $previewContainer: null,
            $bgEl: null,
            baseuser: JSON.parse(Cookies.get('baseUser')),
            modelName: '',
            diplomasId: '',
            formData: {},
            backgroundUrl: backgroundUrl
        };
    },
    mounted () {
        util.ajax.post('/busine/model/findByOrg', util.toFormData({
            organizeid: this.baseuser.orgId
        })).then(res => {
            let data = res.data.data;
            if (data && data.length === 1) {
                this.makeTemplate = JSON.parse(data[0].content);
                this.formData.id =  data[0].id;
            }
        });

        $('#editor').froalaEditor({
            language: 'zh_cn',
            toolbarButtons: ['color', 'fontFamily', 'fontSize', 'bold'],
            fontFamily: {
                'SimSun': '宋体',
                'SimHei': '黑体',
                'Microsoft YaHei': '微软雅黑',
                'PingFang SC': '苹方',
                'Apple LiGothic Medium': 'test'
            }
        });

        $('#editor').on('froalaEditor.contentChanged', (e, editor, keyupEvent) => {
            if (this.activeSpriteIndex > -1) {
                let currSprite = this.makeTemplate.sprites[this.activeSpriteIndex];
                currSprite.content = editor.html.get(true);
                if (currSprite.name === 'name' || currSprite.name === 'diplomas' || currSprite.name === 'theme') {
                    var tdiv = document.createElement('div');
                    tdiv.innerHTML = currSprite.content;
                    currSprite.text = tdiv.innerText;
                }
            }
        });

        this.$previewContainer = this.$el.querySelector('.make-preview');
        this.$bgEl = this.$el.querySelector('.bg-image');

        this.$bgEl.addEventListener('load', () => {
            this.$nextTick(() => {
                this.fitBg();
            });
        });

        this.applyContainerSize();

        window.addEventListener('resize', this.fitBg);
    },
    methods: {
        activateSprite(i) {
            this.activeSpriteIndex = i;

            let currSprite = this.makeTemplate.sprites[i];
            if (currSprite && (currSprite.type === 'text' || currSprite.type === 'variable')) {
                $('#editor').froalaEditor('html.set', currSprite.content);
            }
        },
        addText(){
            this.makeTemplate.sprites.push({
                type: 'text',
                content: '<span style="font-size: 15px;">请输入内容</span>',
                x: 0,
                y: 0
            });
            this.activateSprite(this.makeTemplate.sprites.length - 1);
        },
        addVariable (i) {
            if (!this.variableExist(i)) {
                let variable = this.variables[i];
                let text = variable.placeholder;
                this.makeTemplate.sprites.push({
                    type: 'variable',
                    name: variable.name,
                    text: text,
                    content: '<span style="font-size: 15px;">' + text + '</span>',
                    x: 0,
                    y: 0
                });
                this.activateSprite(this.makeTemplate.sprites.length - 1);
            }
        },
        variableExist (i) {
            let addedVars = this.makeTemplate.sprites.filter((item) => item.type === 'variable');
            if (addedVars.length > 0) {
                return addedVars.findIndex(item => item.name && item.name === this.variables[i].name) > -1;
            } else {
                return false;
            }
        },
        getSpriteStyle(sprite) {
            let style = {
                transform: `translateX(${sprite.x * this.render.bgScale}px) translateY(${sprite.y * this.render.bgScale}px)`
            };
            if (sprite.type === 'picture') {
                style.width = `${sprite.width * this.render.bgScale}px`;
                style.height = `${sprite.height * this.render.bgScale}px`
            }
            return style;
        },
        removeSprite() {
            this.makeTemplate.sprites.splice(this.activeSpriteIndex, 1);
            this.activateSprite(this.makeTemplate.sprites.length - 1);
        },

        spriteMouseDown (e, i) {

            this.drag.draggingIndex = i;
            this.drag.mouseDownX = e.clientX;
            this.drag.mouseDownY = e.clientY;

            let currSprite = this.makeTemplate.sprites[this.drag.draggingIndex];

            let targetEl = e.path[0],
                targetElClassList = targetEl.className.split(/\s+/);
            if (targetElClassList.indexOf('resizer') > -1) {
                // 调整大小
                this.drag.resizer = ['nw', 'ne', 'sw', 'se'].find(item => {
                    return targetElClassList.indexOf(item) > -1;
                });

                this.drag.mouseDownSpriteWidth = currSprite.width;
                this.drag.mouseDownSpriteHeight = currSprite.height;

                this.spriteRatio = currSprite.width / currSprite.height;
            } else {
                // 拖拽位置
                this.drag.resizer = '';
            }

            this.drag.mouseDownSpriteX = currSprite.x;
            this.drag.mouseDownSpriteY = currSprite.y;

            document.addEventListener('mousemove', this.spriteMouseMove);
            document.addEventListener('mouseup', this.spriteMouseUp);
        },
        spriteMouseMove (e) {
            let currSprite = this.makeTemplate.sprites[this.drag.draggingIndex],
                offsetX = e.clientX - this.drag.mouseDownX,
                offsetY = e.clientY - this.drag.mouseDownY;
            if (this.drag.resizer === '') {
                currSprite.x = this.drag.mouseDownSpriteX + offsetX / this.render.bgScale;
                currSprite.y = this.drag.mouseDownSpriteY + offsetY / this.render.bgScale;
            } else {
                let deltaX = 0, deltaY = 0;
                if (Math.abs(offsetX) > Math.abs(offsetY)) {
                    deltaX = offsetX / this.render.bgScale;
                    deltaY = (offsetX / this.spriteRatio) / this.render.bgScale;

                    if (['ne', 'sw'].indexOf(this.drag.resizer) > -1) {
                        deltaY = -deltaY;
                    }
                } else {
                    deltaY = offsetY / this.render.bgScale;
                    deltaX = (offsetY * this.spriteRatio) / this.render.bgScale;

                    if (['ne', 'sw'].indexOf(this.drag.resizer) > -1) {
                        deltaX = -deltaX;
                    }
                }
                switch (this.drag.resizer) {
                    case 'nw':
                        currSprite.x = this.drag.mouseDownSpriteX + deltaX;
                        currSprite.y = this.drag.mouseDownSpriteY + deltaY;
                        currSprite.width = this.drag.mouseDownSpriteWidth - deltaX;
                        currSprite.height = this.drag.mouseDownSpriteHeight - deltaY;
                        break;
                    case 'ne':
                        // currSprite.x = this.drag.mouseDownSpriteX + deltaX;
                        currSprite.y = this.drag.mouseDownSpriteY + deltaY;
                        currSprite.width = this.drag.mouseDownSpriteWidth + deltaX;
                        currSprite.height = this.drag.mouseDownSpriteHeight - deltaY;
                        break;
                    case 'sw':
                        currSprite.x = this.drag.mouseDownSpriteX + deltaX;
                        // currSprite.y = this.drag.mouseDownSpriteY + deltaY;
                        currSprite.width = this.drag.mouseDownSpriteWidth - deltaX;
                        currSprite.height = this.drag.mouseDownSpriteHeight + deltaY;
                        break;
                    case 'se':
                        // currSprite.x = this.drag.mouseDownSpriteX + deltaX;
                        // currSprite.y = this.drag.mouseDownSpriteY + deltaY;
                        currSprite.width = this.drag.mouseDownSpriteWidth + deltaX;
                        currSprite.height = this.drag.mouseDownSpriteHeight + deltaY;
                        break;
                }
            }
        },
        spriteMouseUp (e) {
            document.removeEventListener('mousemove', this.spriteMouseMove);
            document.removeEventListener('mouseup', this.spriteMouseUp);
        },

        applyContainerSize () {
            let rect = this.$previewContainer.getBoundingClientRect();
            this.render.previewContainerWidth = rect.width - 20;
            this.render.previewContainerHeight = rect.height - 20;
        },

        fitBg () {
            this.applyContainerSize();

            // if (this.render.bgOriginWidth === 0) {
            let newImg = new Image();
            newImg.onload = () => {
                this.render.bgOriginWidth = newImg.width;
                this.render.bgOriginHeight = newImg.height;
                fit.call(this);
            };
            newImg.src = this.backgroundUrl;
            // } else {
            //     fit.call(this);
            // }

            function fit() {
                if (this.render.previewContainerWidth / this.render.previewContainerHeight > this.render.bgOriginWidth / this.render.bgOriginHeight) {
                    // portrait
                    this.render.bgScale = this.render.previewContainerHeight / this.render.bgOriginHeight;
                } else {
                    // landscape
                    this.render.bgScale = this.render.previewContainerWidth / this.render.bgOriginWidth;
                }
            }
        },
        save () {
            let makeTemplate = this.makeTemplate;
            let formData = {};
            for (let key in this.formData) {
                formData[key] = this.formData[key];
            }
            formData['orgId'] = this.baseuser.orgId;
            formData['createtime'] = getDate.getDate(formData['createtime'], 'time');
            formData['updatetime'] = getDate.getDate(formData['updatetime'], 'time');
            formData['content'] = JSON.stringify(makeTemplate);
            util.ajax.post('/busine/model/save', util.toFormData(formData)).then(res => {
                if (res.data.message === 'SUCCESS') {
                    this.formData.id = res.data.data.id;
                    this.$Message.success('保存成功！');
                } else {
                    this.$Message.warning(res.data.message || '未知错误！');
                }
            });
        }
    },
    computed: {
        getTextStyle() {
            return {transform: `scale(${this.render.bgScale})`};
        },
        previewContainerStyle() {
            return {
                width: `${this.render.bgOriginWidth * this.render.bgScale}px`,
                height: `${this.render.bgOriginHeight * this.render.bgScale}px`
            };
        }
    },
    beforeDestroy() {
        window.removeEventListener('resize', this.fitBg);
    }
};